package com.gengyun.gengyunacquistion.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gengyun.gengyunacquistion.mapper.AcquisitionCollectHistoryMapper;
import com.gengyun.gengyunacquistion.mapper.AcquisitionMapper;
import com.gengyun.gengyunacquistion.pojo.*;
import com.gengyun.gengyunacquistion.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j

public class AcquisitionCollectHistoryServiceImpl implements IAcquisitionCollectHistoryService{

    @Autowired
    AcquisitionCollectHistoryMapper acquisitionCollectHistoryMapper;

    @Autowired
    @Qualifier("collectHistoryServiceImpl")
    ICollectHistoryService collectHistoryService;

    @Autowired
    ICollectHistoryIndicatorsService collectHistoryIndicatorsService;

    @Autowired
    IRecordService recordService;

    /**
     * 获取上一次获取数据的时间戳, 用于接着获取数据
     * @return
     */
    public String getLastTimestamp() {
        return acquisitionCollectHistoryMapper.selectById(3).getLastTimestamp();
    }



    public void setEndTimestamp(String endTimestamp) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        recordService.updateById(new RecordTime(3, endTimestamp, sf.format(new Date(Long.parseLong(endTimestamp)))));
//        if (endTimestampUpdate.size() > 0) {
//
//            recordService.updateById(new RecordTime(1, endTimestamp, sf.format(Collections.max(endTimestampUpdate))));
//        }
    }



    /**
     * 将json数据保存到txt文档中，
     * @Transactional(rollbackFor = Exception.class)
     * @param content  filePath
     */
    public static boolean createJsonFile(String content, String filePath) {

        // 标记文件生成是否成功
        boolean flag = true;
        // 生成json格式文件
        try {
            // 保证创建一个新文件
            File file = new File(filePath);
            if (!file.getParentFile().exists()) { // 如果父目录不存在，创建父目录
                file.getParentFile().mkdirs();
            }
            if (file.exists()) { // 如果已存在,删除旧文件
                file.delete();
            }
            file.createNewFile();
            // 将格式化后的字符串写入文件
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(content);
            write.flush();
            write.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }




    /**
     * 处理接口获取到的json数据, 这里开启事务管理
     * @Transactional(rollbackFor = Exception.class)
     * @param content
     */
    @Transactional(rollbackFor = Exception.class)
    public void JsonHandler(String content, String endTimestamp) {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Map<String, String> plotCrop = new HashMap<>();
        plotCrop.put( "16085","雪川哈9-新建1");
        plotCrop.put( "16086","雪川哈9-新建2");
        plotCrop.put( "16080","雪川哈6-新建1");
        plotCrop.put( "16081","雪川哈6-新建2");
        plotCrop.put( "16650","雪川哈6-新建3");
        plotCrop.put( "16651","雪川哈6-新建4");
        plotCrop.put( "16652","雪川哈6-新建5");
        plotCrop.put( "16653","雪川哈6-新建6");
        plotCrop.put( "16654","雪川哈6-新建7");

      //  System.out.println(content);

        JSONObject jsonObject = JSON.parseObject(content);
        JSONObject collectHistoryData = jsonObject.getJSONObject("data");
        JSONArray collectHistoryArray =null;
        JSONArray indicatorsArray =null;
        if (collectHistoryData != null)
        {
            collectHistoryArray = collectHistoryData.getJSONArray("indicatorCollects");
            indicatorsArray = collectHistoryData.getJSONArray("indicators");
        }

        if(collectHistoryArray!=null)
        {
            List<CollectHistory> collectHistoryList = handleCollectHistoryArray(collectHistoryArray);


            /**
             * 如果不是null, 就插入, 否则会报错, 批处理至少要有一条数据
             * 顺便更新一下数据库 endTimestamp 更新的问题
             */
            List<Long> endTimestampUpdate = new ArrayList<>();

            if (collectHistoryList.size() > 0) {
                collectHistoryService.saveBatch(collectHistoryList, collectHistoryList.size());

                System.out.println("1:");

            }
        }
        if(indicatorsArray!=null){
            List<CollectHistoryIndicators> indicatorsList = handleIndicatorsArray(indicatorsArray);


            /**
             * 如果不是null, 就插入, 否则会报错, 批处理至少要有一条数据
             * 顺便更新一下数据库 endTimestamp 更新的问题
             */
            List<Long> endTimestampUpdate = new ArrayList<>();

            if (indicatorsList.size() > 0) {
                collectHistoryIndicatorsService.saveBatch(indicatorsList, indicatorsList.size());

                System.out.println("1:");

            }
        }




    }


    /**

     * @return
     */
    private static List<CollectHistory> handleCollectHistoryArray(JSONArray collectHistoryArray) {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<CollectHistory> collectHistoryList = new ArrayList<>();

        for (int i = 0; i < collectHistoryArray.size(); i++) {
            JSONObject history = (JSONObject) collectHistoryArray.get(i);
            String collectID = history.getString("collectID");
            String cropsRotationPlotId = history.getString("collectImages");
            Long collectMode = Long.parseLong(history.getString("collectMode"));
            String collectOrdinalstr = history.getString("collectOrdinal");
            Long collectOrdinal = Long.valueOf(-1);
            if(collectOrdinalstr != null)
            {
                collectOrdinal = Long.parseLong(collectOrdinalstr);
            }

            String collectTimestamp = history.getString("collectTimestamp");
            Long collectUserID = Long.parseLong(history.getString("collectUserID"));

            String collectUserName = history.getString("collectUserName");
            String createTimestamp = history.getString("createTimestamp");
            Long evaluated = Long.parseLong(history.getString("evaluated"));
            String originalCollectID = history.getString("originalCollectID");
            String testingCode = history.getString("testingCode");
            String testingStatus = history.getString("testingStatus");
            String testingSubmitTimestamp = history.getString("testingSubmitTimestamp");


            CollectHistory collectHistory = new CollectHistory(null,
                    collectID,cropsRotationPlotId,collectMode,collectOrdinal,
                    collectTimestamp,collectUserID,collectUserName,createTimestamp,
                    evaluated,originalCollectID,testingCode,testingStatus,
                    testingSubmitTimestamp
            );

            collectHistoryList.add(collectHistory);
        }
        return  collectHistoryList;
    }


    private static List<CollectHistoryIndicators> handleIndicatorsArray(JSONArray indicatorsArray) {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<CollectHistoryIndicators> indicatorsList = new ArrayList<>();

        for (int i = 0; i < indicatorsArray.size(); i++) {
            JSONObject history = (JSONObject) indicatorsArray.get(i);
            String collectID = history.getString("collectID");
            String collectImages = history.getString("collectImages");
            String createTimestamp = history.getString("createTimestamp");
            String cropsRotationPlotId = history.getString("cropsRotationPlotID");
            String digitValue = history.getString("digitValue");
            String indicatorID = history.getString("indicatorID");
            String indicatorValueID = history.getString("indicatorValueID");
            String remark = history.getString("remark");
            String textValue = history.getString("textValue");
            String valueDeterminationFlags = history.getString("valueDeterminationFlags");
            Long valueDeterminationType = Long.parseLong(history.getString("valueDeterminationType"));

            CollectHistoryIndicators collectHistoryIndicators = new CollectHistoryIndicators(null,
                    collectID,collectImages,createTimestamp,cropsRotationPlotId,
                    digitValue,indicatorID,indicatorValueID,remark,
                    textValue,valueDeterminationFlags,valueDeterminationType
            );

            indicatorsList.add(collectHistoryIndicators);
        }
        return  indicatorsList;
    }


}